import React, { useEffect, useState } from 'react';
import { Modal, StyleSheet, TouchableOpacity } from 'react-native';
import { ScrollView, Text, View } from 'native-base';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { FasterImageView } from '@candlefinance/faster-image';
import { CommonStyle } from '../../../common/commonStyle.ts';
import Ionicons from 'react-native-vector-icons/Ionicons';
import HomeRequest from '../../../request/homeRequest.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { useReactive } from 'ahooks';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import Tools from '../../../utils/Tools.ts';
import { updateShoppingCartSku } from '../../../redux/reducers/app.ts';

let skuSelectionPopupInstance: any = null;

interface IState {
  data?: IProductInformation;
  skuData?: IObtainProductSpecificationsRes;
  selectSkuKey: string[];
  nums: number;
}
const SkuSelectionPopup = () => {
  const shoppingCart = useSelector((state: RootState) => state.shoppingCart);
  const dispatch = useDispatch<AppDispatch>();
  const [visible, setVisible] = useState(false);
  const state = useReactive<IState>({ selectSkuKey: [], nums: 1 });

  const show = (data: IProductInformation) => {
    state.data = data;
    fetchObtainProductSpecifications(data.goodsId);
  };
  const hide = () => {
    setVisible(false);
    state.data = undefined;
    state.nums = 1;
  };
  skuSelectionPopupInstance = { show, hide };

  // 获得产品规格
  const fetchObtainProductSpecifications = (goodsId: number) => {
    Loading.show();
    HomeRequest.ObtainProductSpecifications({ goodsId })
      .then((res) => {
        state.skuData = res.data;
        state.selectSkuKey = Object.keys(state.skuData.variantMap)[0].split(':');
        const key = state.selectSkuKey.join(',').replace(/,/g, ':');
        if (state.skuData?.variantMap[key]) {
          state.data = { ...state.data!, active: state.skuData?.variantMap[key].active, sku: key, variantId: state.skuData?.variantMap[key].variantId };
        }
        setVisible(true);
        Loading.hide();
      })
      .catch(() => {
        Loading.hide();
      });
  };

  // 判断规格是否不可选
  const hasSpecValDisable = (specVal: string, index: number) => {
    const keysArray: string[][] = Object.keys(state.skuData!.variantMap).map((key) => key.split(':'));
    return !keysArray.find((item) => item[index] === specVal);
  };

  // 规格选择
  const handleSelectSpec = (specVal: string, index: number) => {
    state.selectSkuKey[index] = specVal;
    const key = state.selectSkuKey.join(',').replace(/,/g, ':');
    if (state.skuData?.variantMap[key]) {
      state.data = { ...state.data!, active: state.skuData?.variantMap[key].active, sku: key, variantId: state.skuData?.variantMap[key].variantId };
    }
  };

  // 渲染产品规格价格
  // && (state.data.goodsType === 1 || state.data.goodsType === 2)
  const renderPrice = () => {
    if (!state.data) return <></>;
    if (Tools.hasActiveRange(state.data!, shoppingCart, state.nums - 1, true)) {
      return (
        <Text fontWeight={'bold'} color={CommonStyle.price} marginRight={2}>
          ¥ {state.data!.active.activePrice}
        </Text>
      );
    } else {
      return (
        <Text fontWeight={'bold'} color={CommonStyle.price} marginRight={2}>
          ¥ {state.data!.salePrice}
        </Text>
      );
    }
  };

  // 渲染产品规格折扣
  const renderingDiscount = () => {
    if (!state.data) return <></>;
    if (Tools.hasActiveRange(state.data!, shoppingCart, state.nums - 1, true)) {
      return (
        <View borderRadius={2} width={100} height={5} flexDirection={'row'} alignItems={'center'} paddingX={1} color={'#eb5449'} borderWidth={0.5} borderColor={CommonStyle.price}>
          <AntDesign name={'tago'} color={CommonStyle.price} />
          <Text marginLeft={1} fontSize={10} color={CommonStyle.price}>
            {((state.data.active.activePrice / state.data.price) * 10).toFixed(2)}折，限{state.data.active.maxNum}份
          </Text>
        </View>
      );
    } else if (state.data.salePrice !== state.data.price) {
      return (
        <View borderRadius={2} width={70} height={5} flexDirection={'row'} alignItems={'center'} paddingX={1} color={'#eb5449'} borderWidth={0.5} borderColor={CommonStyle.price}>
          <AntDesign name={'tago'} color={CommonStyle.price} />
          <Text marginLeft={1} fontSize={10} color={CommonStyle.price}>
            {((state.data.salePrice / state.data.price) * 10).toFixed(2)}折
          </Text>
        </View>
      );
    }
  };

  // 加入购物车
  const handleAddToShoppingCart = () => {
    dispatch(updateShoppingCartSku({ type: 'add', data: { ...state.data!, nums: state.nums } }));
    hide();
  };

  return (
    <React.Fragment>
      <Modal transparent={true} visible={visible} animationType="fade" onRequestClose={() => hide()}>
        <View style={styles.overlay}>
          <View style={styles.container}>
            {state.data && (
              <View flexDirection={'row'} marginBottom={4}>
                <FasterImageView
                  style={{ width: 80, height: 80 }}
                  source={{
                    url: state.data.mainImage,
                    transitionDuration: 0.3,
                    resizeMode: 'cover',
                    borderRadius: 8,
                    cachePolicy: 'discWithCacheControl',
                    showActivityIndicator: true,
                  }}
                />
                <View flex={1} marginLeft={2}>
                  <View flexDirection={'row'} justifyContent={'space-between'} width={'100%'}>
                    <Text flex={1} numberOfLines={1} fontWeight={'bold'}>
                      {state.data.name}
                    </Text>
                    {state.data.visitFlag !== 0 && (
                      <View>
                        <Text fontSize={10} borderWidth={0.5} borderColor={CommonStyle.lightGray} borderRadius={4} paddingX={1}>
                          服务上门
                        </Text>
                      </View>
                    )}
                  </View>
                  {state.data.introduce && (
                    <View width={'100%'} paddingY={1}>
                      <Text fontSize={10} numberOfLines={2} backgroundColor={'#ec820d'} color={CommonStyle.lightGray}>
                        {state.data.introduce}
                      </Text>
                    </View>
                  )}
                  {state.data.remark && (
                    <View width={'100%'} paddingY={1}>
                      <Text fontSize={10} numberOfLines={2} backgroundColor={'#ec820d'} color={CommonStyle.lightGray}>
                        {state.data.remark}
                      </Text>
                    </View>
                  )}
                </View>
              </View>
            )}
            <ScrollView maxHeight={350}>
              {state.skuData?.specList.map((item, index) => {
                return (
                  <React.Fragment key={item.specId}>
                    <Text mb={2}>{item.specName}</Text>
                    <View flexDirection={'row'} flexWrap={'wrap'} marginBottom={4}>
                      {item.specValList.map((_item) => {
                        // 存在即是不可选
                        if (hasSpecValDisable(_item.specVal, index)) {
                          return (
                            <Text style={[styles.skuText, styles.skuTextDisable]} key={_item.specValId}>
                              {_item.specVal}
                            </Text>
                          );
                        } else {
                          return (
                            <TouchableOpacity onPress={() => handleSelectSpec(_item.specVal, index)} key={_item.specValId}>
                              <Text style={[styles.skuText, state.selectSkuKey[index] === _item.specVal ? styles.skuTextActive : undefined]}>{_item.specVal}</Text>
                            </TouchableOpacity>
                          );
                        }
                      })}
                    </View>
                  </React.Fragment>
                );
              })}
            </ScrollView>
            <View flexDirection={'row'} justifyContent={'space-between'} alignItems={'center'} mt={4}>
              <View flexDirection={'row'} alignItems={'center'}>
                {renderPrice()}
                {renderingDiscount()}
              </View>
              <View flexDirection={'row'}>
                <Ionicons
                  name={'remove-circle'}
                  size={26}
                  color={CommonStyle.mainColor}
                  onPress={() => {
                    state.nums > 1 && state.nums--;
                  }}
                />
                <Text mx={2}>{state.nums}</Text>
                <Ionicons name={'add-circle'} size={26} color={CommonStyle.mainColor} onPress={() => state.nums++} />
              </View>
            </View>
            <View flexDirection={'row'} mt={4}>
              <TouchableOpacity style={{ flex: 1, backgroundColor: '#FFC300', borderBottomLeftRadius: 16, borderTopLeftRadius: 16 }} onPress={handleAddToShoppingCart}>
                <Text textAlign={'center'} py={2}>
                  加入购物车
                </Text>
              </TouchableOpacity>
              <TouchableOpacity style={{ flex: 1, backgroundColor: CommonStyle.mainColor, borderBottomRightRadius: 16, borderTopRightRadius: 16 }}>
                <Text textAlign={'center'} py={2} color={'white'}>
                  立即下单
                </Text>
              </TouchableOpacity>
            </View>
          </View>
          <View marginTop={30}>
            <AntDesign name={'closecircleo'} color={'white'} size={35} onPress={() => hide()} />
          </View>
        </View>
      </Modal>
    </React.Fragment>
  );
};

// 全局方法用于调取组件的实例
export const ShowSkuSelectionPopup = {
  show: (data: IProductInformation) => {
    if (skuSelectionPopupInstance) {
      skuSelectionPopupInstance.show(data);
    }
  },
  hide: () => {
    if (skuSelectionPopupInstance) {
      skuSelectionPopupInstance.hide();
    }
  },
};

const styles = StyleSheet.create({
  overlay: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0, 0, 0, 0.5)' },
  container: { width: '95%', backgroundColor: '#fff', borderRadius: 10, padding: 16 },
  card: { paddingVertical: 12, backgroundColor: 'white', borderRadius: 8 },
  productInfo_top: { flexDirection: 'row', width: '100%', paddingHorizontal: 4 },
  skuText: { minWidth: 100, textAlign: 'center', borderColor: '#c5c1c1', borderWidth: 0.5, marginRight: 10, borderRadius: 4, paddingVertical: 8 },
  skuTextActive: { backgroundColor: '#FFFBF0', color: '#ED8A2A', borderColor: '#E0B83E' },
  skuTextDisable: { color: '#a8a7a7', borderColor: '#F1F1F1' },
});

export default SkuSelectionPopup;
